﻿@using SimpleIdServer.IdServer.Website.Resources;
@using SimpleIdServer.IdServer.Website.Stores.UserStore;
@inherits Fluxor.Blazor.Web.Components.FluxorComponent
@inject IDispatcher dispatcher
@inject IState<SearchUserSessionsState> userSessionsState
@inject IState<UpdateUserState> updateUserState
@inject ContextMenuService contextMenuService
@inject NotificationService notificationService

<p class="text-muted">@Global.UserSessionsDescription</p>

<RadzenButton class="mb-1" Click="@(args => RevokeSessions())" Icon="delete" Text="@Global.RevokeSessions" ButtonStyle="ButtonStyle.Primary" Size="ButtonSize.Medium"></RadzenButton>
<RadzenDataGrid @ref="sessionsGrid"
            AllowFiltering="true"
            AllowColumnResize="true"
            AllowAlternatingRows="false"
            AllowSorting="true"
            PageSize="30"
            AllowPaging="true"
            PagerHorizontalAlign="HorizontalAlign.Left"
            ShowPagingSummary="true"
            IsLoading="@updateUserState.Value.IsUpdating"
            Count="@userSessionsState.Value.Count"
            Data="@userSessionsState.Value.UserSessions"
            LoadData="@LoadData"
            RowRender="@RowRender"
            TItem="UserSession"
            ColumnWidth="300px">
    <Columns>
        <RadzenDataGridColumn TItem="UserSession" Property="AuthenticationDateTime" Title="@Global.AuthenticationTime" Filterable="false" Sortable="true" FormatString="{0:dd/M/yyyy HH:mm:ss}" SortOrder="SortOrder.Descending" Width="80px" />
        <RadzenDataGridColumn TItem="UserSession" Property="SessionId" Title="@Global.Identifier" Filterable="false" Sortable="false" Width="80px" />
        <RadzenDataGridColumn TItem="UserSession" Title="@Global.Clients" Filterable="false" Sortable="false" Width="80px">
            <Template Context="data">
                @foreach(var clientId in data.ClientIds)
                {
                    <RadzenLink Text="@clientId" Path="@($"/clients/{clientId}/settings")" />
                }
            </Template>
        </RadzenDataGridColumn>
        <RadzenDataGridColumn TItem="UserSession" Property="ExpirationDateTime" Title="@Global.ExpirationTime" Filterable="false" Sortable="false" FormatString="{0:dd/M/yyyy HH:mm:ss}" Width="80px" />
        <RadzenDataGridColumn TItem="UserSession" Title="@Global.State" Filterable="false" Sortable="false" Width="80px">
            <Template Context="data">
                @if (data.State == UserSessionStates.Rejected)
                {
                    <RadzenBadge Text="@Global.Rejected" IsPill="true" BadgeStyle="BadgeStyle.Danger" />
                }
                else if (data.State == UserSessionStates.Active && data.ExpirationDateTime > DateTime.Now)
                {
                    <RadzenBadge Text="@Global.Active" IsPill="true" BadgeStyle="BadgeStyle.Success"></RadzenBadge>
                }
                else
                {
                    <RadzenBadge Text="@Global.Expired" IsPill="true" BadgeStyle="BadgeStyle.Danger"></RadzenBadge>
                }
            </Template>
        </RadzenDataGridColumn>
        <RadzenDataGridColumn TItem="UserSession" Filterable="false" Sortable="false" Width="80px" TextAlign="TextAlign.Center">
            <Template Context="data">
                @if (data.State == UserSessionStates.Active && data.ExpirationDateTime > DateTime.Now)
                {
                    <RadzenButton Icon="more_vert" Click="@(args => ShowMoreContextMenu(data, args))" />
                }
            </Template>
        </RadzenDataGridColumn>
    </Columns>
</RadzenDataGrid>

@code {
    private SimpleIdServer.IdServer.Domains.User _user;
    RadzenDataGrid<UserSession> sessionsGrid;

    [Parameter]
    public SimpleIdServer.IdServer.Domains.User User
    {
        get
        {
            return _user;
        }
        set
        {
            if(value != null && _user == null && sessionsGrid != null)
            {
                _user = value;
                sessionsGrid?.Reload();
            }
        }
    }

    protected override void OnAfterRender(bool firstRender)
    {
        base.OnAfterRender(firstRender);
        if (firstRender)
        {
            SubscribeToAction<RevokeUserSessionSuccessAction>((act) =>
            {
                notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Success, Summary = Global.UserSessionRejected });
                StateHasChanged();
            });
        }
    }

    void ShowMoreContextMenu(UserSession session, MouseEventArgs args)
    {
        contextMenuService.Open(args, new List<ContextMenuItem>
        {
            new ContextMenuItem { Text = Global.Reject, Value = 1 }
        }, (a) => {
        if (a.Value.Equals(1))
        {
            var act = new RevokeUserSessionAction { UserId = User.Id, SessionId = session.SessionId };
            dispatcher.Dispatch(act);
            contextMenuService.Close();
        }
    });
    }

    void LoadData(LoadDataArgs args)
    {
        if (User == null) return;
        var act = new SearchUserSessionsAction { Filter = args.Filter, OrderBy = args.OrderBy, Skip = args.Skip, Take = args.Top, UserId = User.Id };
        dispatcher.Dispatch(act);
    }

    void RowRender(RowRenderEventArgs<UserSession> row)
    {
        const string className = "class";
        if (row.Attributes.ContainsKey(className))
            row.Attributes.Remove(className);
    }

    void RevokeSessions()
    {
        var act = new RevokeUserSessionsAction { UserId = User.Id };
        dispatcher.Dispatch(act);
    }
}